package com.itic.mall.system.tixian.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.exports.ExportExcel;
import com.itic.appbase.applications.exports.ExportExcelWithTemplet;
import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.UserSessionHelper;
import com.itic.mall.system.marketuser.persistence.model.MarketUser;
import com.itic.mall.system.marketuser.service.MarketUserService;
import com.itic.mall.system.profitmoney.persistence.model.ProfitMoney;
import com.itic.mall.system.profitmoney.persistence.model.ProfitMoneyExample;
import com.itic.mall.system.profitmoney.persistence.model.ProfitMoneyExample.Criteria;
import com.itic.mall.system.profitmoney.service.ProfitMoneyService;
import com.itic.mall.system.tixian.persistence.model.Tixian;
import com.itic.mall.system.tixian.persistence.model.TixianExample;
import com.itic.mall.system.tixian.persistence.model.TixianVo;
import com.itic.mall.system.tixian.service.TixianService;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;


@Controller
@RequestMapping(value="/system/tixian")
public class TixianController
     extends BaseController {
	protected static String Url = "http://120.55.205.5/webservice/sms.php?method=Submit";//发送短信的URL
	private static final String APP_KEY = "97b60aeccea9d113d6a1b164";
	
	private static final String SECREAT = "fc9a01780fdeb90b43e736f3";
    @Autowired
    private TixianService tixianService;
    @Autowired
    private ProfitMoneyService profitMoneyService;
    @Autowired
    private MarketUserService marketUserService;
    @Autowired
  	protected OutCommonService outCommonService;
    //导出常量
    private static final String TEMP = "bzmc";//备注名称
    private static final String DATALIST = "dataList";//数据常量
       
       //////////////////////////////////////////////////////常量区////////////////////////////////////////////////////////////////
       private static final String MODEL_NAME_CHINA = "提现管理";//中文名
       private static final String MODEL_NAME＿ENGLISH = "tixian";//英文名
       private static final String PAGE_COMMON_PATH = "/mall/system/tixian/tixian";//通用路径
       private static final String COMMON_URL = "/system/tixian/";//通用路径


       //////////////////////////////////////////////////////页面跳转区////////////////////////////////////////////////////////////
      
       /*
        * 主页面
        */
       @RequestMapping(value="/init")
       public String init(Model model){
       	model.addAttribute("name_china", MODEL_NAME_CHINA);
       	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
       	model.addAttribute("common_url", COMMON_URL);
       	return PAGE_COMMON_PATH+"Main";
       }
       
       
       /*
        * 查看页面
        */
       @RequestMapping(value="/initView")
       public String initView(String id , Model model){
       	    if( StringHelper.isNotBlank(id) ) {
	       		
	       		Tixian temp  = tixianService.get(id);
	       		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
	       		model.addAttribute("name_china", MODEL_NAME_CHINA);
	           	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
	           	model.addAttribute("common_url", COMMON_URL);
        	}else {
                throw new ParameterErrorException();
            }
       	
         	return PAGE_COMMON_PATH+"View";
       }
       
       
       /*
        * 查看页面
        */
       @RequestMapping(value="/initFafang")
       public String initFafang(String id , Model model){
       	    if( StringHelper.isNotBlank(id) ) {
	       		
	       		Tixian temp  = tixianService.get(id);
	       		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
	       		model.addAttribute("name_china", MODEL_NAME_CHINA);
	           	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
	           	model.addAttribute("common_url", COMMON_URL);
        	}else {
                throw new ParameterErrorException();
            }
       	
         	return PAGE_COMMON_PATH+"Fafang";
       }
       
       /*
        * 查看页面
        */
       @RequestMapping(value="/initEdit")
       public String initEdit(String id , Model model){
       	    if( StringHelper.isNotBlank(id) ) {
	       		
	       		Tixian temp  = tixianService.get(id);
	       		model.addAttribute("editData",iticJsonMapper.toJson(temp));
	       		model.addAttribute("name_china", MODEL_NAME_CHINA);
	           	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
	           	model.addAttribute("common_url", COMMON_URL);
        	}else {
                throw new ParameterErrorException();
            }
       	
         	return PAGE_COMMON_PATH+"Edit";
       }
       
       
       //////////////////////////////////////////////////////业务代码区////////////////////////////////////////////////////////////
       
       
       
       /**
        * <p>Title:queryCondition </p>
        * <p>Description:封装查询条件 </p>
        * @param jzdw
        * @param jzdwExample
        * @return
        */
       private TixianExample queryCondition(HttpServletRequest request,Tixian temp,String startTime,String endTime,String ffstartTime,String ffendTime) {
       	
         	// 参数处理
           TixianExample example = new TixianExample();
           // 按创建时间倒序
           example.setOrderByClause("CREATE_TIME ASC");
           
           com.itic.mall.system.tixian.persistence.model.TixianExample.Criteria criteria = example.createCriteria().andIsEffectiveEqualTo( DBConst.TRUE );
         
           // 查询条件
           if ( null != temp ) {
        	   if( StringHelper.isNotBlank(temp.getUserName()) ){
        		   criteria.andUserNameLike("%"+temp.getUserName()+"%");
        	   }
        	   if( StringHelper.isNotBlank(temp.getIsGive()) ){
        		   criteria.andIsGiveEqualTo(temp.getIsGive());
        	   }
        	   if( StringHelper.isNotBlank(temp.getZfbName()) ){
        		   criteria.andZfbNameLike("%"+temp.getZfbName()+"%");
        	   }
        	   if( StringHelper.isNotBlank(temp.getZfbAccount()) ){
        		   criteria.andZfbAccountLike("%"+temp.getZfbAccount()+"%");
        	   }
        	   //大于开始时间
        	   if( StringHelper.isNotBlank(startTime) ){
        		   criteria.andCreateTimeGreaterThanOrEqualTo(DateHelper.getDateByStringDate(startTime+IticConst.START_TIME_SUFFIX));
        	   }
        	    //小于开始时间
        	   if( StringHelper.isNotBlank(endTime) ){
        		   criteria.andCreateTimeLessThanOrEqualTo(DateHelper.getDateByStringDate(endTime+IticConst.END_TIME_SUFFIX));
        	   }
        	   //大于发放时间
        	   if( StringHelper.isNotBlank(ffstartTime) ){
        		   criteria.andGiveTimeGreaterThanOrEqualTo(DateHelper.getDateByStringDate(ffstartTime+IticConst.START_TIME_SUFFIX));
        	   }
        	   //小于发放时间
        	   if( StringHelper.isNotBlank(ffendTime) ){
        		   criteria.andGiveTimeLessThanOrEqualTo(DateHelper.getDateByStringDate(ffendTime+IticConst.END_TIME_SUFFIX));
        	   }
           }
           return example;
       }
       
       /**
        * 
        * @param goldType
        * @param request
        * @return
        */
       @RequestMapping(value = "/list")
       @ResponseBody
       public Map<String, Object> list(Tixian temp, HttpServletRequest request, String startTime,String endTime,String ffstartTime,String ffendTime ){
           // 声明返回对象
           Map<String, Object> resultMap = new HashMap<String, Object>();
           
           
           TixianExample example = this.queryCondition(request,temp,startTime,endTime,ffstartTime,ffendTime);
           // 封装分页参数
           example = this.handlePageQuery(request, example);
           
           
           // 获取信息总条数
           int total = tixianService.count(example);
           
           // 获取数据
           List<Tixian> list = tixianService.list(example);
           
           
           // 数据返回处理
           resultMap.put(IticConst.TOTAL_RECORDS, total);
           resultMap.put(IticConst.DISPLAY_RECORDS, total);
           resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
           resultMap.put(IticConst.DATA, list);
           return resultMap;

       }
       
       
       /**
        * 
        * @param goldType
        * @param request
        * @return
        */
       @RequestMapping(value = "/listProfit")
       @ResponseBody
       public Map<String, Object> listProfit( String userId, HttpServletRequest request ){
           // 声明返回对象
           Map<String, Object> resultMap = new HashMap<String, Object>();
           
           ProfitMoneyExample example = new ProfitMoneyExample();
           example.setOrderByClause("CREATE_TIME DESC");
           Criteria criteria = example.createCriteria();
           criteria.andIsEffectiveEqualTo(DBConst.TRUE);
           criteria.andMarketUserIdEqualTo(userId);
           // 封装分页参数
           example = this.handlePageQuery(request, example);
           
           
           // 获取信息总条数
           int total = profitMoneyService.count(example);
           
           // 获取数据
           List<ProfitMoney> list = profitMoneyService.list(example);
           
           
           // 数据返回处理
           resultMap.put(IticConst.TOTAL_RECORDS, total);
           resultMap.put(IticConst.DISPLAY_RECORDS, total);
           resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
           resultMap.put(IticConst.DATA, list);
           return resultMap;

       } 
       

       /**
        * 删除
        * 
        */
       @RequestMapping(value = "/fafang")
       @ResponseBody
       public Map<String, String> fafang(String id) {
            Map<String, String> resultMap = new HashMap<String, String>();
            String result = ResponseCode.SERVER_ERROR.getCode();

            Tixian temp = tixianService.get(id);
            temp.setIsGive("1");
            temp.setUpdateTime(new Date());
            
            String userId = temp.getUserId();
            MarketUser marketUser = marketUserService.get(userId);
            
            if( null != marketUser ){
            	String userPhone = marketUser.getUserPhone();
            	if( StringHelper.isNotBlank(userPhone) ){
            		sendMassage(userPhone,"您申请的"+temp.getMoney()+"元已到账，请登入友惠家云店app查看！");
            	}
            	//发送app消息
            	pushMsg(marketUser.getId(),"您申请的"+temp.getMoney()+"元已到账，请登入友惠家云店app查看！");
            }
            
            result = tixianService.edit(temp);
           
            
           resultMap.put(IticConst.RESULT, result);
           return resultMap;
       }
       
       /**
        * 删除
        * 
        */
       @RequestMapping(value = "/fafangBatch")
       @ResponseBody
       public Map<String, String> fafangBatch(String ids) {
            Map<String, String> resultMap = new HashMap<String, String>();
            String result = ResponseCode.SUCCESS.getCode();

            if( StringHelper.isNotBlank(ids) ){
            	String[] split = ids.split(",");
            	for( int i=0; i<split.length; i++ ){
            		fafBatch(split[i]);
            	}
            }
            resultMap.put(IticConst.RESULT, result);
            return resultMap;
       }
       
       public void fafBatch(String id){
    	   
    	   Tixian temp = tixianService.get(id);
           temp.setIsGive("1");
           temp.setNote("批量付款");
           temp.setUpdateTime(new Date());
           
           String userId = temp.getUserId();
           MarketUser marketUser = marketUserService.get(userId);
           
           if( null != marketUser ){
           	String userPhone = marketUser.getUserPhone();
           	if( StringHelper.isNotBlank(userPhone) ){
           		sendMassage(userPhone,"您申请的"+temp.getMoney()+"元已到账，请登入友惠家云店app查看！");
           	}
           	//发送app消息
           	pushMsg(marketUser.getId(),"您申请的"+temp.getMoney()+"元已到账，请登入友惠家云店app查看！");
           }
           tixianService.edit(temp);
       }
       
       /**
        * 删除
        * 
        */
       @RequestMapping(value = "/falsess")
       @ResponseBody
       public Map<String, String> falsess(String id,String note) {
           Map<String, String> resultMap = new HashMap<String, String>();
           String result = ResponseCode.SERVER_ERROR.getCode();

           Tixian temp = tixianService.get(id);
           temp.setIsGive("2");
           temp.setNote(note);
           temp.setUpdateTime(new Date());
           //temp.setNote("支付宝账号名与支付宝账号不符，请重新提交！");
           result = tixianService.falseee(temp);
           
           String userId = temp.getUserId();
           MarketUser marketUser = marketUserService.get(userId);
           
           if( null != marketUser ){
        	   
           		String userPhone = marketUser.getUserPhone();
	           	if( StringHelper.isNotBlank(userPhone) ){
	           		sendMassage(userPhone,"您申请的"+temp.getMoney()+"元已退回到账户余额，原因："+ note +"，请登入友惠家云店app重新申请！");
	           	}
	           	
	           	//发送app消息
	           	pushMsg(marketUser.getId(),"您申请的"+temp.getMoney()+"元已退回到账户余额，原因："+ note +"，请登入友惠家云店app重新申请！");
	           	
           }
           resultMap.put(IticConst.RESULT, result);
           return resultMap;
       }
       
       
       /**
        * 删除
        * 
        */
       @RequestMapping(value = "/edit")
       @ResponseBody
       public Map<String, String> edit(Tixian tixian) {
           Map<String, String> resultMap = new HashMap<String, String>();
           String result = ResponseCode.SERVER_ERROR.getCode();

           result = tixianService.edit(tixian);
           
           resultMap.put(IticConst.RESULT, result);
           return resultMap;
       }
       
       /**
        * 发送验证码通用方法（注册与修改密码需要用到）
        * @param telphone  手机号码
        * @return
        */
       public void sendMassage(String telphone,String msg){
    	    HttpClient client = new HttpClient(); 
			PostMethod method = new PostMethod(Url); 
				
			//client.getParams().setContentCharset("GBK");		
			client.getParams().setContentCharset("UTF-8");
			method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

			//String content = new String("您的验证码是："+codeCont+"。请不要把验证码泄露给其他人。"); 
		    String content = new String(msg);
			// 您的验证码是：【变量】，3分钟有效时间，请不要把验证码泄露给其他人。
		    NameValuePair[] data = {//提交短信
				    //new NameValuePair("account", "cf_jdhj"), 
				    //new NameValuePair("password", "a123456"), //密码可以使用明文密码或使用32位MD5加密
				    new NameValuePair("account", "C11714710"), 
				    new NameValuePair("password", "85202a35086eb358e717dbf9ebc6e9bc"), //密码可以使用明文密码或使用32位MD5加密
				    //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
				    new NameValuePair("mobile", telphone), 
				    new NameValuePair("content", content),
			};
			
			method.setRequestBody(data);		
			
			
			try {
				client.executeMethod(method);	
				 
				String SubmitResult =method.getResponseBodyAsString();
						
				//System.out.println(SubmitResult);

				Document doc = DocumentHelper.parseText(SubmitResult); 
				Element root = doc.getRootElement();


				String code = root.elementText("code");	
				//String msg = root.elementText("msg");	
				//String smsid = root.elementText("smsid");	
				
				
				//System.out.println(code);
				//System.out.println(msg);
				//System.out.println(smsid);
							
				if("2".equals(code)){
					System.out.println("");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}	
       	
       }
       
       /**
        * exp
        * 
        */
       @RequestMapping(value = "/exp")
       @ResponseBody
       public void exp(HttpServletRequest request, HttpServletResponse response,Tixian temp,String startTime,String endTime,String ffstartTime,String ffendTime) {
       	 try {        	
            	 // 参数处理
       		    TixianExample example=new TixianExample();         
                example = this.queryCondition(request,temp, startTime, endTime, ffstartTime, ffendTime);           
                List<TixianVo> list = new ArrayList<TixianVo>();
                // 获取数据
                List<Tixian> listTemp = tixianService.list(example);   
                if( listTemp.size()>0 ){
                	for( Tixian ttmp : listTemp ){
                		
                		TixianVo vo = new TixianVo();
                		vo.setUserId(ttmp.getUserId());
                		vo.setUserName(ttmp.getUserName());
                		vo.setType(ttmp.getType());
                		vo.setTimes(ttmp.getTimes());
                		vo.setMoney(ttmp.getMoney());
                		vo.setFeeMoney(ttmp.getFeeMoney());
                	    vo.setCreateTime(DateHelper.getDateStringByDate(ttmp.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                	    vo.setGiveTime(ttmp.getGiveTime());
                	    vo.setZfbName(ttmp.getZfbName());
                	    vo.setZfbAccount(ttmp.getZfbAccount());
                		if( "0".equals(ttmp.getIsGive() ) ){
                			vo.setIsGive("未发放");
                		}else if("1".equals(ttmp.getIsGive())){
                			vo.setIsGive("发放成功");    
                		}else{
                			vo.setIsGive("发放失败");
                		}
                		vo.setActureName(ttmp.getActureName());
                		vo.setNote(ttmp.getNote());
                		list.add(vo);
                	}
                }
                //导出
                Map<String, Object> exportMap = new HashMap<String, Object>();
                exportMap.put(TEMP, MODEL_NAME＿ENGLISH);
                exportMap.put(DATALIST, list);
                ExportExcel exportExcel = new ExportExcelWithTemplet();
                exportExcel.exportExcel(exportMap, request, response);
                
            } catch (Exception e) {
           	    throw new RuntimeException("[TempletController | exp 模板示例导出异常]");
            } 
       }
       
       
       /**
        * 发送一条邮件提醒
        * @param email
        * @param msg
        */
       public void sendEmail( String email,String msg){
    	   
       }
       
       
       public void pushMsg( String userId ,String text ){
       	//推送消息到云店主
   		 JPushClient jpushClient = new JPushClient(SECREAT, APP_KEY, null, ClientConfig.getInstance());

   	    // For push, all you need do is to build PushPayload object.
   	    //PushPayload payload = buildPushObject_all_all_alert( text );
   	    
   		//PushPayload payload = buildPushObject_ios_audienceMore_messageWithExtras( userId,text );
   		PushPayload payload = buildPushObject_all_alias_alert(userId,text);
   	    try {
   	        PushResult tmpres = jpushClient.sendPush(payload);
   	       
   	        System.out.println(tmpres);
   	        //LOG.info("Got result - " + result);

   	    } catch (APIConnectionException e) {
   	        // Connection error, should retry later
   	        //LOG.error("Connection error, should retry later", e);
   	    	System.out.println(1);
   	    } catch (APIRequestException e) {
   	        // Should review the error, and fix the request
   	        //LOG.error("Should review the error, and fix the request", e);
   	        //LOG.info("HTTP Status: " + e.getStatus());
   	       // LOG.info("Error Code: " + e.getErrorCode());
   	        //LOG.info("Error Message: " + e.getErrorMessage());
   	    	System.out.println(2);
   	    }
   	    
       }
       
       public static PushPayload buildPushObject_all_alias_alert( String userId, String text ) {
           return PushPayload.newBuilder()
                   .setPlatform(Platform.all())
                   .setAudience(Audience.alias(userId))
                   .setNotification(Notification.alert(text))
                   .build();
       }

}